package org.example;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ProducerMain {
	public static void main(String[] args) {
		SpringApplication.run(ProducerMain.class,args);
	}

	// Spring AMQP 配置
//	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) 
	{
		RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
		rabbitTemplate.setMandatory(true); // 开启强制回调
		
		// 设置 ConfirmCallback
		rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
			if (ack) {
				System.out.println("消息到达交换机，ID: " + correlationData.getId());
			} else {
				System.err.println("消息未到达交换机，原因: " + cause);
			}
		});

		// 设置 ReturnsCallback
		rabbitTemplate.setReturnsCallback(returned -> {
			System.err.println("消息未路由到队列: " + returned.getMessage());
		});

		return rabbitTemplate;
	}
	
}